package com.layui.ad.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.layui.ad.annotation.DataSource;
import com.layui.ad.constant.MenuConstant;
import com.layui.ad.entity.SysAdmin;
import com.layui.ad.entity.SysMenu;
import com.layui.ad.enums.DataSourceEnum;
import com.layui.ad.mapper.SysAdminMapper;
import com.layui.ad.mapper.SysMenuMapper;
import com.layui.ad.query.BaseQuery;
import com.layui.ad.query.MenuQuery;
import com.layui.ad.service.SysMenuService;
import com.layui.ad.utils.JsonResult;
import com.layui.ad.utils.ShiroUtils;
import com.layui.ad.utils.StringUtils;
import com.layui.ad.utils.TreeUtil;
import com.layui.ad.vo.MenuListVo;
import com.layui.ad.vo.SysMenuVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysAdminMapper sysAdminMapper;

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<SysMenuVo> getMenuList() {
        List<SysMenuVo> menuList = this.baseMapper.getMenuList();
        for (SysMenuVo menu : menuList) {
            if (menu.getLevel().equals(3)) {
                SysMenu menuUrl = this.baseMapper.getStartPage(menu.getId());
                if (menuUrl != null) {
                    menu.setUrl(menuUrl.getUrl());
                }
            }
        }

        TreeUtil tree = new TreeUtil();
        List<SysMenuVo> rootMenu = tree.tree(menuList);
        return rootMenu;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<Map<String, Object>> getMenuByPid(Integer pid) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", pid);
//        queryWrapper.eq("mark", 1);
        queryWrapper.orderByDesc("sort");
        List<SysMenu> itemCateList = this.baseMapper.selectList(queryWrapper);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (!itemCateList.isEmpty()) {
            itemCateList.forEach(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", item.getId());
                map.put("name", item.getName());
                mapList.add(map);

                // 获取子级
                List<Map<String, Object>> childrenList = this.getMenuByPid(item.getId());
                if (!childrenList.isEmpty()) {
                    childrenList.forEach(subItem -> {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("id", subItem.get("id"));
                        map1.put("name", "|--" + subItem.get("name"));
                        mapList.add(map1);
                    });
                }

            });
        }
        return mapList;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public SysMenu getStartPage(Integer parentId) {
        return this.baseMapper.getStartPage(parentId);
    }


    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<SysMenuVo> menuTree() {
//        QueryWrapper<SysMenu> wrapper = new QueryWrapper();
//        wrapper.le("type",3);
//        List<SysMenu> menuList = this.baseMapper.selectList(wrapper);

        List<SysMenuVo> menuList = this.baseMapper.getMenuTree();
        for (SysMenuVo nav : menuList) {
            nav.setName(nav.getTitle());
        }
        TreeUtil tree = new TreeUtil();
        List<SysMenuVo> rootMenu = tree.tree(menuList);
        return rootMenu;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public void saveToDb(SysMenu sysMenu) {
        this.baseMapper.insert(sysMenu);
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public Integer updateToDb(SysMenu sysMenu) {
        return this.baseMapper.updateById(sysMenu);
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public Map<String, Object> findByPk(Integer id) {
        Object entity = this.baseMapper.selectById(id);
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(entity), new TypeReference<Map<String, Object>>() {
        });
        return map;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public Boolean drop(Integer id) {
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", id);
        Integer count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            return false;
        }
        Integer delCount = this.baseMapper.deleteById(id);
        if (delCount > 0) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<MenuListVo> getNavbarMenu() {
        Integer adminId = ShiroUtils.getAdminId();
        SysAdmin obj = sysAdminMapper.selectById(adminId);
        String roleIds = obj.getRoleIds();
        // 顶部导航
        List<MenuListVo> menuListVoList = sysMenuMapper.getNavbarMenu(adminId, roleIds, 0);
        if (!menuListVoList.isEmpty()) {
            menuListVoList.forEach(item -> {
                // 模块
                List<MenuListVo> menuListVoList1 = sysMenuMapper.getNavbarMenu(adminId, roleIds, item.getId());
                if (!menuListVoList1.isEmpty()) {
                    menuListVoList1.forEach(subItem -> {
                        // 菜单
                        List<MenuListVo> menuListVoList2 = sysMenuMapper.getNavbarMenu(adminId, roleIds, subItem.getId());
                        if (!menuListVoList2.isEmpty()) {
                            menuListVoList2.forEach(menu -> {
                                // 节点
                                List<MenuListVo> menuListVoList3 = sysMenuMapper.getNavbarMenu(adminId, roleIds, menu.getId());
                                menu.setChildren(menuListVoList3);
                            });
                        }
                        subItem.setChildren(menuListVoList2);
                    });
                    item.setChildren(menuListVoList1);
                }
            });
        }
        return menuListVoList;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult getList(BaseQuery query) {
        MenuQuery menuQuery = (MenuQuery) query;
        // 查询条件
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
//        // 菜单名称
        if (!StringUtils.isEmpty(menuQuery.getName())) {
            queryWrapper.like("name", menuQuery.getName());
        }
        // 类型：1模块 2导航 3菜单 4节点
        if (menuQuery.getType() != null && menuQuery.getType() > 0) {
            queryWrapper.eq("type", menuQuery.getType());
        }
//        // 是否显示：1显示 2不显示
//        if (menuQuery.getStatus() != null && menuQuery.getStatus() > 0) {
//            queryWrapper.eq("status", menuQuery.getStatus());
//        }
//        // 是否公共：1是 2否
//        if (menuQuery.getIsPublic() != null && menuQuery.getIsPublic() > 0) {
//            queryWrapper.eq("is_public", menuQuery.getIsPublic());
//        }
//        queryWrapper.eq("mark", 1);
//        queryWrapper.orderByAsc("sort");

        // 查询数据
        List<SysMenu> menuList = sysMenuMapper.selectList(queryWrapper);
        List<MenuListVo> menuListVoList = new ArrayList<>();
        if (!menuList.isEmpty()) {
            menuList.forEach(item -> {
                MenuListVo menuListVo = new MenuListVo();
                // 拷贝属性
                BeanUtils.copyProperties(item, menuListVo);
                // 类型描述
                if (menuListVo.getType() != null && menuListVo.getType() > 0) {
                    menuListVo.setTypeName(MenuConstant.MENU_TYPE_LIST.get(menuListVo.getType()));
                }
//                // 是否显示描述
//                if (menuListVo.getStatus() != null && menuListVo.getStatus() > 0) {
//                    menuListVo.setStatusName(MenuConstant.MENU_STATUS_LIST.get(menuListVo.getStatus()));
//                }
//                // 是否公共描述
//                if (menuListVo.getIsPublic() != null && menuListVo.getIsPublic() > 0) {
//                    menuListVo.setIsPublicName(MenuConstant.MENU_ISPUBLIC_LIST.get(menuListVo.getIsPublic()));
//                }
//                // 创建人名称
//                if (menuListVo.getCreateUser() != null && menuListVo.getCreateUser() > 0) {
//                    menuListVo.setCreateUserName(AdminUtils.getName((menuListVo.getCreateUser())));
//                }
//                // 更新人名称
//                if (menuListVo.getUpdateUser() != null && menuListVo.getUpdateUser() > 0) {
//                    menuListVo.setUpdateUserName(AdminUtils.getName((menuListVo.getUpdateUser())));
//                }
                // 默认展开
                if (menuListVo.getType() <= 2) {
                    menuListVo.setOpen(true);
                } else {
                    menuListVo.setOpen(false);
                }
                menuListVoList.add(menuListVo);
            });
        }
        return JsonResult.ok(menuListVoList);
    }

    //第二版新增加  菜单的编辑
    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult edit(SysMenu entity) {
        if (entity == null) {
            return JsonResult.fail("实体对象不存在");
        }
        boolean result = false;
        if (entity.getId() != null && entity.getId() > 0) {
            // 修改记录
//            entity.setUpdateUser(ShiroUtils.getAdminId());
//            entity.setUpdateTime(DateUtils.now());
            result = this.updateById(entity);
        } else {
            // 新增记录
//            entity.setCreateUser(ShiroUtils.getAdminId());
//            entity.setCreateTime(DateUtils.now());
//            entity.setMark(1);
            result = this.save(entity);
        }
        if (!result) {
            return JsonResult.fail();
        }
        if (!StringUtils.isEmpty(entity.getUrl()) && !entity.getUrl().equals("#")) {
            String[] urlItem = entity.getUrl().split("/");
            String module = urlItem[1];
            if (!StringUtils.isEmpty(entity.getFuncIds())) {

                //判断原有的节点和现有的节点是否一致,一致的话不进行任何操作,不一致时先进行删除原有的,再新加
                List<Integer> typeList = this.getTypeList(entity.getId());
                String typeString = StringUtils.join(typeList.toArray(), ",");
                if (!entity.getFuncIds().equals(typeString)) {
                    QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("pid", entity.getId());
                    sysMenuMapper.delete(queryWrapper);

                    //执行插入操作
                    String[] funcIds = entity.getFuncIds().split(",");
                    for (String s : funcIds) {
                        SysMenu menu = new SysMenu();
                        if (s.equals("1")) {
                            menu.setName("列表");
                            menu.setUrl(String.format("/%s/list", module));
                            menu.setPermission(String.format("%s:list", module));
                        } else if (s.equals("2")) {
                            menu.setName("添加");
                            menu.setUrl(String.format("/%s/add", module));
                            menu.setPermission(String.format("%s:add", module));
                        } else if (s.equals("3")) {
                            menu.setName("修改");
                            menu.setUrl(String.format("/%s/update", module));
                            menu.setPermission(String.format("%s:update", module));
                        } else if (s.equals("4")) {
                            menu.setName("删除");
                            menu.setUrl(String.format("/%s/delete", module));
                            menu.setPermission(String.format("%s:delete", module));
                        } else if (s.equals("5")) {
                            menu.setName("状态");
                            menu.setUrl(String.format("/%s/status", module));
                            menu.setPermission(String.format("%s:status", module));
                        } else if (s.equals("6")) {
                            menu.setName("批量删除");
                            menu.setUrl(String.format("/%s/update", module));
                            menu.setPermission(String.format("%s:update", module));
                        }
                        menu.setPid(entity.getId());
                        menu.setType(4);
                        menu.setSort(Integer.valueOf(s));
                        menu.setStatus(1);
                        menu.insert();
                    }
                }
            }
        }

        return JsonResult.ok();
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult deleteById(Integer id) {
        if (id == null || id == 0) {
            return JsonResult.fail("记录ID不能为空");
        }
        SysMenu entity = this.getById(id);
        if (entity == null) {
            return JsonResult.fail("记录不存在");
        }

        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", id);
        Integer count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            return JsonResult.fail("分类个有子类");
        }
        Integer delCount = this.baseMapper.deleteById(id);
        if (delCount > 0) {
            return JsonResult.ok();
        }
        return JsonResult.fail("删除失败");
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult setStatus(SysMenu menuVo) {
        if (sysMenuMapper.updateById(menuVo) > 0) {
            return JsonResult.ok();
        } else {
            return JsonResult.fail();
        }
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<SysMenu> getMenuListByAdminId(Integer adminId) {
        return sysMenuMapper.getMenuListByAdminId(adminId);
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<Integer> getTypeList(Integer pid) {
        List<Integer> typeList = new ArrayList<>();
        if (pid != null && pid > 0) {
            QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pid", pid);
            List<SysMenu> menuList = sysMenuMapper.selectList(queryWrapper);
            if (menuList != null) {
                menuList.forEach(item -> {
                    switch (item.getName()) {
                        case "列表":
                            typeList.add(1);
                            break;
                        case "添加":
                            typeList.add(2);
                            break;
                        case "修改":
                            typeList.add(3);
                            break;
                        case "删除":
                            typeList.add(4);
                            break;
                        case "状态":
                            typeList.add(5);
                            break;
                        case "批量删除":
                            typeList.add(6);
                            break;
                    }
                });
            }
        }
        return typeList;
    }

}
